extends Control

var maxLen: int = 70
var fingerFlg = -1
var vectorsee: Vector2
@onready var joystick: Sprite2D = $Joystick
@onready var point: Sprite2D = $Joystick/point


func _input(event: InputEvent) -> void:
	# #检测到正在拖动或按下
	control_nocamera(event)
	
			
# 控制摇杆
func control_nocamera(event: InputEvent) -> void:
	#偏移量
	#var offset = (Vector2(1152,648)/camera.get_zoom())/2
	# var maxLent = maxLen/camera.get_zoom().x
	var maxLent = maxLen
	var new_pos = Vector2.ZERO
	#var screensize = get_viewport().size
	#print(get_canvas_transform())
	

	if event is InputEventScreenTouch and event.is_pressed():
		# 点击相对相机位置
		new_pos = event.position
		if new_pos.x > 320.0/2:
			return
		
		joystick.visible = true
		joystick.set_global_position (new_pos)
		# position = new_pos
	
	#检测到正在拖动或按下
	if event is InputEventScreenDrag or (event is InputEventScreenTouch and event.is_pressed()):
		# 点击相对相机位置
		new_pos = event.position
		#计算鼠标击置和摇杆中心的距离
		var mounse_len = (new_pos-joystick.global_position).length()
		
		#print("鼠标离摇杆中心距离：", mounse_len, new_pos)
		if mounse_len <= maxLent or fingerFlg==event.get_index():
			fingerFlg = event.get_index()
			
			point.set_global_position(new_pos) 
			var pos = get_postion_pos()
			if pos.length() > maxLent:
				point.position = pos.normalized()*maxLent
		
		#映射到输入
		var vector = point.position/maxLen
		if vector.x>0:
			Input.action_release("move_left")
			Input.action_press("move_right",vector.x)
		else :
			Input.action_release("move_right")
			Input.action_press("move_left",-vector.x)
		if vector.y>0:
			Input.action_release("move_up")
			Input.action_press("move_down",vector.y)
		else:
			Input.action_release("move_down")
			Input.action_press("move_up",-vector.y)
			
	elif event is InputEventScreenTouch and not event.is_pressed() and fingerFlg==event.get_index():
		#松开幕就重置
		fingerFlg = -1
		point.position= Vector2.ZERO
		joystick.visible = false
		Input.action_release("move_up")
		Input.action_release("move_down")
		Input.action_release("move_left")
		Input.action_release("move_right")


# 获取位置
func get_postion_pos() -> Vector2:
	return point.position
